import ConfirmModal from '@/components/ConfirmModal';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { queryCompanies } from '@/pages/SystemUser/service';
import { Auths, Role } from '@/utils/types.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Tooltip } from 'antd';
import { useRef, useState } from 'react';
import { useModel } from 'umi';
import { queryScheduleManagement, removeSchedule } from '../service';
import { ScheduleManagementTableItem } from '../types.d';
import UpdateSchedule from './components/UpdateSchedule';

const ScheduleList = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.scheduleManagement || []) : new Set();
  const ifDelete = auths.has(Auths.DELETE);
  const ifModify = auths.has(Auths.MODIFY);

  const [currItem, setCurrItem] = useState<ScheduleManagementTableItem>();
  const [updateVisible, setUpdateVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<ScheduleManagementTableItem>[] = [
    {
      title: 'id',
      hideInTable: true,
      hideInSearch: true,
      dataIndex: '_id',
      width: 80,
    },
    {
      title: '归属公司',
      dataIndex: 'ownerId',
      hideInForm: true,
      width: 80,
      hideInTable: currUser?.role !== Role.ADMIN,
      hideInSearch: currUser?.role !== Role.ADMIN,
      fieldProps: { showSearch: true },
      render: (_, record) => record.ownerId,
      debounceTime: 300,
      request: (val) => queryCompanies(val.keyWords),
    },
    {
      title: '收费员',
      dataIndex: 'name',
      hideInForm: true,
      width: 80,
      align: 'center',
    },
    {
      title: '员工号',
      dataIndex: 'jobNo',
      width: 80,
      align: 'center',
      hideInForm: true,
    },
    {
      title: '日期',
      dataIndex: 'day',
      hideInForm: true,
      width: 80,
      align: 'center',
      valueType: 'date',
    },
    {
      title: '星期几',
      dataIndex: 'dayOfWeek',
      hideInSearch: true,
      width: 80,
      hideInForm: true,
      align: 'center',
      renderText: (text) => {
        switch (text) {
          case 2:
            return '星期一';
          case 3:
            return '星期二';
          case 4:
            return '星期三';
          case 5:
            return '星期四';
          case 6:
            return '星期五';
          case 7:
            return '星期六';
          case 1:
            return '星期日';
          default:
            return '格式异常';
        }
      },
    },
    {
      title: '班次',
      dataIndex: 'shiftConfigName',
      hideInForm: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '执勤车场',
      dataIndex: 'parkingLotIds',
      hideInSearch: true,
      hideInForm: true,
      align: 'center',
      width: 140,
      // renderText: (_, record) =>
      //   ,
      render: (_, record) => {
        const msg = record?.allParkValid
          ? '全路段'
          : record?.parkingLots?.map((item) => item.parkingLotName).join(',');
        return msg?.length > 40 ? <Tooltip title={msg}>{msg.slice(0, 36) + '...'}</Tooltip> : msg;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
      width: 100,
      align: 'center',
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      width: 80,
      render: (_, record, x, action) => {
        if (!ifDelete && !ifModify) return [<PlaceHolderCpn />];
        return [
          ifModify && (
            <a
              onClick={() => {
                setCurrItem(record);
                setUpdateVisible(true);
              }}
            >
              编辑
            </a>
          ),
          ifDelete && (
            <ConfirmModal
              reload={() => action?.reload()}
              operFunc={async () => await removeSchedule(record._id)}
              text={`是否确定要删除 ${record.name} 在 ${record.day} 的排班`}
            />
          ),
        ];
      },
    },
  ];

  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: '收费人员排班管理列表',
        breadcrumb: {
          routes: [
            {
              path: '/',
              breadcrumbName: '首页',
            },
            {
              path: '/staff',
              breadcrumbName: '员工管理',
            },
            {
              path: '/staff/schedule',
              breadcrumbName: '排班管理',
            },
          ],
        },
      }}
    >
      <ProTable<ScheduleManagementTableItem>
        style={{ whiteSpace: 'nowrap' }}
        columns={columns}
        search={{
          labelWidth: 'auto',
        }}
        scroll={{ x: true }}
        actionRef={actionRef}
        rowKey="_id"
        columnEmptyText="暂无数据"
        dateFormatter="string"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryScheduleManagement(param, sort);
          return res;
        }}
      />
      {updateVisible && currItem && (
        <UpdateSchedule
          currItem={currItem}
          visible={updateVisible}
          close={() => {
            setUpdateVisible(false);
            setCurrItem(undefined);
          }}
          reload={() => {
            actionRef.current?.reload();
          }}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default ScheduleList;
